<?php

namespace Payment\Client;

use Payment\CloseContext;
use Payment\Common\PayException;
use Payment\Config;

/**
 * 关闭订单
 *
 * Class Close
 * @package Payment\Client
 */
class Close {

    private static $supportChannel = [
        Config::SW_CHARGE, //扫呗支付关闭订单
        Config::SW_T_CHARGE, //扫呗支付(3.0)关闭订单
        Config::FU_CHARGE, //富友支付关闭订单
		Config::LTF_CHARGE,//联拓富支付关闭订单
		Config::YS_CHARGE,//易生支付关闭订单
    ];

    /**
     * @var  CloseContext
     */
    protected static $instance;


    protected static function getInstance($channel, $config){

        if (is_null(self::$instance)) {
            static::$instance = new CloseContext();

            try {
                static::$instance->initCloseHandler($channel, $config);
            } catch (PayException $e) {
                throw $e;
            }
        }

        return static::$instance;
    }

    /**
     * @param string $channel
     * @param array $config
     * @param array $metadata
     *
     * @return mixed
     * @throws PayException
     */
    public static function run($channel, $config, $metadata)
    {
        if (! in_array($channel, self::$supportChannel)) {
            throw new PayException('sdk当前不支持该支付渠道，当前仅支持：' . implode(',', self::$supportChannel));
        }

        try {
            $instance = self::getInstance($channel, $config);

            $ret = $instance->close($metadata);
        } catch (PayException $e) {
            throw $e;
        }

        return $ret;
    }
}
